package com.chixing.ih.util;

import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘岩
 * Date: 2020-09-23
 * Time: 22:00
 *
 * @version 1.0
 */
@Component
public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    @Autowired
    JwtUtil jwtUtil;

    public boolean doAuthorization(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) return false;
        try {
            String token = this.getToken(request);
            Claims claims = jwtUtil.parseToken(token);
            if (jwtUtil.isNeedReToken(claims)) {
                setToken(response, jwtUtil.createJWT(claims));
            }
            request.setAttribute("userId", jwtUtil.getId(claims));
            return true;
        } catch (Exception e) {
            logger.warn("没有登录或者登录过期");
            response.setStatus(401);
        }
        return false;
    }

    public void setToken(HttpServletResponse response, String token) {
        response.setHeader("token", token);
    }

    public String getToken(HttpServletRequest request) {
        return request.getHeader("Authorization");
    }
}
